<?php
namespace app\api\controller;

use think\Controller;
use think\Request;
use think\Session;
use think\Db;

/**
 * 通用上传接口
 * Class Upload
 * @package app\api\controller
 */
class Index extends Controller
{
    public function index()
    { /*广告后台首页顶部菜单*/
        $now              = date('Y-m-d', strtotime("-1 days"));
        $data['register'] = Db:: table('ad_user_info')->whereTime('register_time', '<= time', "$now")->count('id');
        $data['userinc']  = Db::table('ad_user_info')->whereTime('register_time', 'today')->count('uid');
        $data['active']   = Db::table('ad_user')->whereTime('last_login', 'today')->count('id');
        $data['adsinc']   = Db::table('ad_list')->whereTime('create_time', 'today')->count('id');
        $data['share']    = Db::table('ad_fx')->whereTime('create_time', 'today')->count('id');
        return json(['code' => 200, 'info' => 'success', 'data' => $data]);
    }


    /*
     *  平台注册总用户*/

    public function ad_register()
    {
        //广告主数量 adv    自媒体数量 media    有效广告主数量 validadv   有效自媒体数量 validmedia
        $data['adv']       = Db::table('ad_user_info')->where('type', 1)->count('uid');
        $data['media']     = Db::table('ad_user_info')->where('type', 2)->count('uid');
        $data['validadv']  = Db::table('ad_banner_money')
            ->alias('m')
            ->join('ad_user_info u', 'm.uid = u.uid')
            ->where(['u.type' => 1])
            ->group('u.uid')
            ->count('u.uid');
        $data['valimedia'] = Db::table('ad_banner_money')
            ->alias('m')
            ->join('ad_user_info u', 'm.uid = u.uid')
            ->where(['u.type' => 2])
            ->group('u.uid')
            ->count('u.uid');

        return json(['code' => 200, 'info' => 'success', 'data' => $data]);

    }

//今日新增用户
    public function ad_userincrement()
    {

        $data['newadv_day']  = Db::table('ad_user_info')->whereTime('register_time', 'today')->where('type',
            1)->count('id');
        $data['newadv_week'] = Db::table('ad_user_info')->whereTime('register_time', 'week')->where('type',
            1)->count('id');
        $data['newadv_mon']  = Db::table('ad_user_info')->whereTime('register_time', 'month')->where('type',
            1)->count('id');

        $data['newmedia_day']  = Db::table('ad_user_info')->whereTime('register_time', 'today')->where('type',
            2)->count('uid');
        $data['newmedia_week'] = Db::table('ad_user_info')->whereTime('register_time', 'week')->where('type',
            2)->count('uid');
        $data['newmedia_mon']  = Db::table('ad_user_info')->whereTime('register_time', 'month')->where('type',
            2)->count('uid');

        return json(['code' => 200, 'info' => 'success', 'data' => $data]);
    }

//今日活跃用户  本周 本月
    public function ad_active()
    {
        $data['active_week'] = Db::table('ad_user')->whereTime('last_login', 'week')->count('id');
        $data['active_mon']  = Db::table('ad_user')->whereTime('last_login', 'month')->count('id');

        return json(['code' => 200, 'info' => 'success', 'data' => $data]);
    }

//今日新增广告数量
    public function ad_adsincrement()
    {
        $data['newads_week']  = Db::table('ad_list')->whereTime('create_time', 'week')->count('id');
        $data['newads_mon']   = Db::table('ad_list')->whereTime('create_time', 'month')->count('id');
        $data['newads_sum']   = Db::table('ad_list')->count('id');
        $data['newads_valid'] = Db::table('ad_list')->where('status', 2)->count('id');

        return json(['code' => 200, 'info' => 'success', 'data' => $data]);
    }

    //今日广告转发次数
    public function ad_share()
    {
        $data['share_week']  = Db::table('ad_fx')->whereTime('create_time', 'week')->count('id');
        $data['share_mon']   = Db::table('ad_fx')->whereTime('create_time', 'month')->count('id');
        $data['share_sum']   = Db::table('ad_fx')->count('id');
        $data['click_valid'] = Db::table('ad_click_get')->count('id');//改成有效点击
        return json(['code' => 200, 'info' => 'success', 'data' => $data]);
    }

    //广告地域投放
    public function ad_puton()
    {
        $data['adv_sum']  = Db::table('ad_user_info')->where('type', 1)->count('id');
        $data['adv_cent'] = Db::query("select p.province ,count('uid') as count from ad_user_info u,ad_provinces p where u.province = p.provinceid and u.type = 1 Group BY province");

        $data['media_sum']  = Db::table('ad_user_info')->where('type', 2)->count('id');
        $data['media_cent'] = Db::query("select p.province ,count('uid') as count from ad_user_info u,ad_provinces p where u.province = p.provinceid and u.type = 2  Group BY province");

        return json(['code' => 200, 'info' => 'success', 'data' => $data]);
    }

    //折线图 搜索
    public function graph_search(Request $request)
    {
//总注册用户
        $data_type  = $request->param('data_type') ?: 'register';
        $start_time = $request->param('start_time') ?: '';
        $end_time   = $request->param('end_time') ?: '';
        $where      = [];
        $days       = 0;

        if ($start_time and $end_time) {
            $time1 = strtotime($start_time);
            $time2 = strtotime($end_time);
            //$where['register_time'] = ['between',"$time1,$time2"];
            $days = $this->daysbetweendates($time1, $time2);
        }

        $all_month = [];
        for ($i = $days ?: 7; $i >= 0; $i--) {

            $str_time    = $this->getDayTimeStamps($end_time, $i);
            $k           = date("m", $str_time['lastday']);
            $all_month[] = $k . '-' . date("d", $str_time['lastday']);
            // var_dump($str_time);exit();

            if ($data_type == 'useinc') {
                $data[$k . '-' . $i]['count'] = Db::table('ad_user_info')
                    ->where('register_time', 'between', [$str_time['firstday'], $str_time['lastday']])
                    ->count('uid');
            } else {
                if ($data_type == 'active') {
                    $data[$k . '-' . $i]['count'] = Db::table('ad_user')
                        ->where('last_login', 'between', [$str_time['firstday'], $str_time['lastday']])
                        ->group('last_login')
                        ->count('id');
                } else {
                    if ($data_type == 'advinc') {
                        $data[$k . '-' . $i]['count'] = Db::table('ad_list')
                            ->where('create_time', 'between', [$str_time['firstday'], $str_time['lastday']])
                            ->count('id');
                    } else {
                        if ($data_type == 'share') {
                            $data[$k . '-' . $i]['count'] = Db::table('ad_fx')
                                ->where('create_time', 'between', [$str_time['firstday'], $str_time['lastday']])
                                ->count('uid');
                        } else {
                            if ($data_type == 'register') {
                                $data[$k . '-' . $i]['count'] = Db::table('ad_user_info')
                                    ->where('register_time', 'between', [$str_time['firstday'], $str_time['lastday']])
                                    ->count('uid');
                            }
                        }
                    }
                }
            }
        }
        $output     = [];
        $all_data   = [];
        $final_data = [];

        foreach ($data as $key => $val) {
            $output['count'][]         = ($val['count']);
            $all_data['caculate_date'] = $output;
        }
        foreach ($all_data['caculate_date'] as $key => $val) {
            if ($key == 'count') {
                $final_data[$k]['name'] = '活跃数';
                $final_data[$k]['type'] = 'line';
                $final_data[$k]['data'] = $val;
            }
        }

        $final_data               = array_values($final_data);
        $return_data['all_data']  = $final_data;
        $return_data['all_month'] = $all_month;
        $return_data['chinese']   = ['活跃数'];

        return json(['code' => 200, 'info' => 'success', 'data' => $return_data]);
    }

    public function getDayTimeStamps($date2, $i)
    {
        $t                = strtotime("$date2 -$i day");
        $data['firstday'] = mktime(0, 0, 0, date("m", $t), date("d", $t), date("Y", $t));
        $data['lastday']  = mktime(23, 59, 59, date("m", $t), date("d", $t), date("Y", $t));
        return $data;
    }

    public function daysbetweendates($date1, $date2)
    {

        $days = ceil(abs($date1 - $date2) / 86400);
        return (int)$days;
    }


    //全部用户
    public function alluser(Request $request)
    {
        $page  = $request->param('page') ?: 1;
        $limit = $request->param('limit') ?: 10;

        $user = Db::table('ad_user_info')
            ->alias('ui')
            ->field('ui.uid,ui.true_name ,ui.user_type,( SELECT NAME FROM ad_industry WHERE id = job_three) job, ui.phone , 
                  ( SELECT province FROM ad_provinces WHERE provinceid = ui.province) AS province ,
                  ( SELECT city FROM ad_cities WHERE cityid = ui.city) AS city,
                  ( SELECT count(1) people FROM ad_user_info WHERE fu_invitation = ui.invitation) people_num,ui.register_time,ui.invitation')
            ->paginate($limit, false, ['page' => $page]);
        return json(['code' => 200, 'info' => 'success', 'data' => $user]);
    }

    //全部用户的查看
    public function alluser_look(Request $request)
    {
        $page       = $request->param('page') ?: 1;
        $limit      = $request->param('limit') ?: 10;
        $invitation = $request->param('invitation');
        $user       = Db::table('ad_user_info')
            ->alias('ui')
            ->where(['ui.fu_invitation' => $invitation])
            ->field('ui.uid,ui.true_name ,( SELECT NAME FROM ad_industry WHERE id = job_three) job , ui.phone , 
                  ( SELECT province FROM ad_provinces WHERE provinceid = ui.province) AS province ,
                  ( SELECT city FROM ad_cities WHERE cityid = ui.city) AS city,
                  ( SELECT sum(money) FROM ad_user_money WHERE uid = ui.uid) touru_money ,ui.register_time')
            ->paginate($limit, false, ['page' => $page]);
        return json(['code' => 200, 'info' => 'success', 'data' => $user]);
    }


    //自媒体
    public function media(Request $request)
    {
        $page  = $request->param('page') ?: 1;
        $limit = $request->param('limit') ?: 10;

        $user = Db::table('ad_user_info')
            ->alias('ui')
            ->where(['ui.type' => 2])
            ->field('ui.uid,ui.true_name ,( SELECT NAME FROM ad_industry WHERE id = job_three) job , ui.phone ,
                  ( SELECT province FROM ad_provinces WHERE provinceid = ui.province) AS province ,
                  ( SELECT city FROM ad_cities WHERE cityid = ui.city) AS city,
                  ( SELECT sum(money) FROM ad_lcb WHERE uid = ui.uid) shouyi_money ,ui.register_time')
            ->paginate($limit, false, ['page' => $page]);
        return json(['code' => 200, 'info' => 'success', 'data' => $user]);
    }

    //广告主
    public function adv(Request $request)
    {
        $page  = $request->param('page') ?: 1;
        $limit = $request->param('limit') ?: 10;

        $user = Db::table('ad_user_info')
            ->alias('ui')
            ->where(['ui.type' => 1])
            ->field('ui.uid,ui.true_name ,( SELECT NAME FROM ad_industry WHERE id = job_three) job , ui.phone , 
                  ( SELECT province FROM ad_provinces WHERE provinceid = ui.province) AS province ,
                  ( SELECT city FROM ad_cities WHERE cityid = ui.city) AS city,
                  ( SELECT sum(money) FROM ad_user_money WHERE uid = ui.uid) touru_money ,ui.register_time')
            ->paginate($limit, false, ['page' => $page]);
        return json(['code' => 200, 'info' => 'success', 'data' => $user]);
    }

    //自媒体或者广告主的查看
    public function other_look(Request $request)
    {
        $uid  = $request->param('uid');
        $type = $request->param('type');
        if ($type == 'media') {//自媒体

            $user['sum_share']   = Db::table('ad_click')->where(['uid' => $uid])->group('ad_id')->count();
            $user['valid_share'] = Db::table('ad_click_get')->where(['uid' => $uid])->count();
            $user['get_money']   = Db::query("select sum(money) as money,channel  from ad_lcb where uid = '$uid' group by channel");
            return json(['code' => 200, 'info' => 'success', 'data' => $user]);
        } else {
            if ($type == 'adv') {

                $user['sum_puton']   = Db::table('ad_list')->where(['uid' => $uid])->count();
                $user['valid_share'] = Db::table('ad_click_get')->where(['uid' => $uid])->count();
                $user['get_route']   = Db::query("select count(id) as count,channel  from ad_click where uid = $uid group by channel");
                return json(['code' => 200, 'info' => 'success', 'data' => $user]);
            }
        }

    }

    //用户 禁用或启用
    public function user_lock(Request $request)
    {
        $uid  = $request->param('uid');
        $lock = $request->param('lock');
        $res  = Db::table('ad_user_info')->where(['uid' => $uid])->update(['is_open' => $lock]);
        if ($res) {
            return json(['code' => 200, 'info' => 'success', 'data' => $res]);
        } else {
            return json(['code' => -1, 'info' => 'error']);
        }
    }

//获取省和市
    public function province(Request $request)
    {
        $data['province'] = Db::table('ad_provinces')->select();
        $data['city']     = Db::table('ad_cities')->select();
        return json(['code' => 200, 'info' => 'success', 'data' => $data]);
    }


    //提现设置
    public function extracts(Request $request)
    {
        $max_money = $request->param('max_money') ?: '';
        $min_money = $request->param('min_money') ?: '';
        $poundage  = $request->param('poundage') ?: '';
        if ($max_money and $min_money and $poundage) {
            Db::table('ad_extract')->where('id', 1)->update([
                'extract_money' => $max_money,
                'extract_poundage' => $poundage,
                'extract_min' => $min_money
            ]);
        }
        $data = Db::table('ad_extract')->find(1);
        return json(['code' => 200, 'info' => 'success', 'data' => $data]);
    }

    //分润设置
    public function divideds(Request $request)
    {
        $divided     = $request->param('divided') ?: '';
        $two_divided = $request->param('two_divided') ?: '';
        $invitation  = $request->param('invitation') ?: '';
        if ($divided and $two_divided and $invitation) {
            Db::table('ad_divided')->where('id', 1)->update([
                'cz_divided' => $divided,
                'cz_two_divided' => $two_divided,
                'cz_invitation' => $invitation
            ]);
        }
        $data = Db::table('ad_divided')->find(1);
        return json(['code' => 200, 'info' => 'success', 'data' => $data]);

    }

    //广告规则和注意力规则
    public function get_regular(Request $request)
    {
        $stay_time   = $request->param('stay_time');
        $stay_length = $request->param('stay_length');
        $gaze_time   = $request->param('gaze_time');
        $gaze_length = $request->param('gaze_length');

        if ($stay_time and $stay_length and $gaze_time and $gaze_length) {
            Db::table('ad_regular')->where('id', 1)->update([
                'stay_time' => $stay_time,
                'stay_length' => $stay_length,
                'gaze_time' => $gaze_time,
                'gaze_length' => $gaze_length
            ]);
        }
        $data = Db::table('ad_regular')->find(1);
        return json(['code' => 200, 'info' => 'success', 'data' => $data]);

    }


    //图片跳转链接
    public function img_link(Request $request)
    {
        $name  = $request->param('name');
        $image = $request->param('image');//图片上传的时候调用通用上传类，将返回的图片路径传过来
        $url   = $request->param('url');

        if ($name and $image and $url) {
            Db::table('ad_banner')->insertGetId([
                'name' => $name,
                'img' => $image,
                'url' => $url,
                'create_time' => time()
            ]);
        }
        $data = Db::table('ad_banner')->select();
        return json(['code' => 200, 'info' => 'success', 'data' => $data]);
    }

    //图片修改
    public function img_update(Request $request)
    {
        $id     = $request->param('id');
        $url    = $request->param('url');
        $is_top = $request->param('is_top');
        $data   = Db::table('ad_banner')->where(['id' => $id])->update(['url' => $url, 'is_top' => $is_top]);
        return json(['code' => 200, 'info' => 'success', 'data' => $data]);
    }

    //图片删除
    public function img_delete(Request $request)
    {
        $id = $request->param('id');
        Db::table('ad_banner')->delete($id);
        $data = Db::table('ad_banner')->select();
        return json(['code' => 200, 'info' => 'success', 'data' => $data]);
    }

    public function getLocation(Request $request)
    {
        $ip  = $request->ip(0, true);//获取真实ip
        $uid = $request->param('uid') ?: 1;//用户uid
        if (empty($uid) || (strcmp($ip, '127.0.0.1') == 0)) {
            return json(['code' => 500, 'info' => 'ip无效或者uid为空']);
        }
        $key = 'e9c94537835cfca4d56663a03331ec2b';
        $url = "http://restapi.amap.com/v3/ip?key=$key&ip=$ip";

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        // 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
        // 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        $result = json_decode($res, true);

        /**
         * 返回的数据
         * array:7 [▼
         * "status" => "1"
         * "info" => "OK"
         * "infocode" => "10000"
         * "province" => "北京市"
         * "city" => "北京市"
         * "adcode" => "110000"
         * "rectangle" => "116.0119343,39.66127144;116.7829835,40.2164962"
         * ]
         */

        $city_name = $result['city'];
        if (empty($city_name)) {
            //todo 无效点击
            return json(['code' => 500, 'info' => '点击无效']);
        }
        $where         = [];
        $where['city'] = ['like', "%{$city_name}%"];
        $find_city = Db::name('cities')->where($where)->field('cityid')->find();//拿到cityid
        if (empty($find_city)) {
            //todo 无效点击
            return json(['code' => 500, 'info' => '点击无效']);
        }
        //根据cityid判断该用户的城市id
        $res_user = Db::name('user_info')->where(['uid' => $uid, 'city' => $find_city['cityid']])->find();
        if ($res_user) {
            //todo 增加有效点击
            return json(['code' => 200, 'info' => '点击有效']);
        }
        //todo 无效点击
        return json(['code' => 500, 'info' => '点击无效']);
    }


}


